package com.hjqjl.whdemo.db.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.blankj.utilcode.util.LogUtils;
import com.hjqjl.whdemo.app.Config;
import com.hjqjl.whdemo.app.MyApplication;
import com.hjqjl.whdemo.db.DatabaseContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DAO {
    private static MyDatabaseHelp helper;
    private static SQLiteDatabase db;
    private Context mContext;


    public DAO(Context context) {
        //helper = new DBHelper(context);
        DatabaseContext dbContext = new DatabaseContext(MyApplication.getInstance(), Config.dbDir);
        this.helper = MyDatabaseHelp.getInstance(dbContext);///单例模式
    }


    /**
     * 查询
     *
     * @param sql       (select * from table where args1=?)
     * @param whereArgs (arg1_value)
     * @return 第一行，第一列记录
     */
    public String exeScalar(String sql, String... whereArgs) {
        String result = "";
        filterWhereArgs(whereArgs);
        db = helper.getWritableDatabase();
        Cursor c = db.rawQuery(sql, whereArgs);
        if (c.moveToNext()) {
            result = c.getString(0);
        }
        closeDb(db, c);
        return result;
    }

    public List<String> exeQueryList(String sql) {
        List<String> result = new ArrayList<String>();
        db = helper.getWritableDatabase();
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            result.add(c.getString(0));
        }
        closeDb(db, c);
        return result;
    }

    /**
     * 输入SQL语句与需要获取的列数进行查询
     *
     * @param sql
     * @param column
     * @return 记录集
     * @throws Exception
     */
    public List<String> exeQueryList(String sql, int column) {
        List<String> result = new ArrayList<String>();
        db = helper.getWritableDatabase();
        Cursor c = db.rawQuery(sql, null);
        try {
            while (c.moveToNext()) {
                String tempStr = "";
                for (int i = 0; i < column; i++) {
                    //第一行前面面不加字符
                    if (i % column == 0) {
                        if ("".equals(c.getString(i))) {
                            tempStr = "";
                        } else {
                            tempStr = c.getString(i);
                        }
                    } else {
                        if ("".equals(c.getString(i))) {
                            tempStr = tempStr + "&&" + " ";
                        } else {
                            tempStr = tempStr + "&&" + c.getString(i);
                        }
                    }
                }
                result.add(tempStr);
            }
        } catch (Exception ex) {
            result.clear();
//			result.add(ex.getMessage());
            closeDb(db, c);
            throw ex;
        }
        closeDb(db, c);
        return result;
    }

    /**
     * 查询
     *
     * @param sql       (select * from table where args1=?)
     * @param whereArgs (arg1_value)
     * @return Cursor记录集
     */
    public List<Map<String, String>> exeQueryList(String sql, List<String> keyList, String... whereArgs) {
        String result = "";
        filterWhereArgs(whereArgs);
        db = helper.getWritableDatabase();
        Cursor c = db.rawQuery(sql, whereArgs);
        List<Map<String, String>> mList = new ArrayList<Map<String, String>>();
        while (c.moveToNext()) {
            int index = 0;
            Map<String, String> mL = new HashMap<String, String>();
            for (String map : keyList) {
                mL.put(map, c.getString(index));
                index++;
            }
            mList.add(mL);
        }
        closeDb(db, c);
        return mList;
    }

    /**
     * 插入数据库
     *
     * @param table
     * @param values
     * @return
     */
    public long insert(String table, ContentValues values) {
        long result = 0L;
        db = helper.getWritableDatabase();
        result = db.insert(table, null, values);
        closeDb(db, null);
        return result;
    }

    /**
     * 事物处理
     *
     * @param sqlList
     * @return
     */
    public Boolean Transaction(List<String> sqlList) {
        long result = 0L;
        db = helper.getWritableDatabase();
        // 开启事务
        db.beginTransaction();
        try {
            for (String sql : sqlList) {
                db.execSQL(sql);
            }
            // 设置事务标志为成功，当结束事务时就会提交事务
            db.setTransactionSuccessful();
            LogUtils.v("事务处理成功");
        } catch (Exception e) {
            LogUtils.v("事务处理失败");
            return false;
        } finally {
            // 结束事务
            db.endTransaction();
            closeDb(db, null);
        }
        return true;
    }

    /**
     * 删除表记录
     *
     * @param table
     * @param values
     * @return 删除记录数
     */
    public int delete(String table, String[] values) {
        int result = 0;
        db = helper.getWritableDatabase();
        result = db.delete(table, null, values);
        return result;
    }

    /**
     * sql语句操作，直接执行sql语句
     *
     * @param sql
     * @return 无返回值
     */
    /**
     * @param sql
     * @throws Exception
     */
    public void execSQL(String sql) throws Exception {
        db = helper.getWritableDatabase();
        try {
            db.execSQL(sql);
            closeDb(db, null);
        } catch (Exception ex) {
            closeDb(db, null);
            throw ex;
        }
    }

    /**
     * 过滤whereArgs中为null的数据项
     *
     * @param whereArgs
     */
    private static void filterWhereArgs(String... whereArgs) {
        if (whereArgs != null && whereArgs.length > 0) {
            for (int i = 0, j = whereArgs.length; i < j; i++) {
                if (whereArgs[i] == null) {
                    whereArgs[i] = "";
                }
            }
        }
    }

    /**
     * 释放数据库资源
     **/
    public void closeDb(SQLiteDatabase db, Cursor c) {
        if (c != null) {
            c.close();
        }
        if (db != null) {
            db.close();
        }
        db.close();
    }

    /**
     * 查询
     */
    public List<String> Query(Boolean isdistinct, String tablename, String[] columnList, String where, String[] whereparams) {
        List<String> rstList = new ArrayList<String>();
        String result = "";
        db = helper.getWritableDatabase();
        Cursor c = db.query(isdistinct, tablename, columnList, where, whereparams, null, null, null, null);
        int i = 0;
        while (c.moveToNext()) {
            result = c.getString(0);
            rstList.add(result);
            i++;
        }
        closeDb(db, c);
        return rstList;

    }

    public void deleteTable(String mTable) {
        db = helper.getWritableDatabase();
        db.execSQL("drop table " + mTable);
    }

    public void clearTable(String mTable) {
        db = helper.getWritableDatabase();
        db.execSQL("delete from " + mTable);
    }
}
